//
//  HJTeasingDetailHeaderView.m
//  project
//
//  Created by jc on 2019/5/7.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJTeasingDetailHeaderView.h"
#import "HJTeasingVC.h"
#import "YFImagePicker.h"
#import "YBImageBrowser.h"


#define imageView_Width (SCREEN_WIDTH -24)
#define margin (10)

@interface HJTeasingDetailHeaderView ()
@property (weak, nonatomic) IBOutlet UIView *titleView;
@property (weak, nonatomic) IBOutlet UILabel *title;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UILabel *placeHolder;
@property (weak, nonatomic) IBOutlet UIView *publicView;
@property (weak, nonatomic) IBOutlet UILabel *countLabel;
@property (weak, nonatomic) IBOutlet UIView *imagesView;

@property (weak, nonatomic) IBOutlet UITextField *phoneNum;
@property (weak, nonatomic) IBOutlet UIButton *commitBtn;
@property (weak, nonatomic) IBOutlet UIView *contactView;
@property (weak, nonatomic) IBOutlet UIButton *addBtn;
@property (weak, nonatomic) IBOutlet UIView *publicTitleView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *addBtn_width;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *addBtn_x;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *addBtn_y;

/**
 图片浏览数组数组
 */
@property (nonatomic, strong) NSArray <YBImageBrowseCellData *> *imageCellDatas;
@property (nonatomic,strong) NSArray * assets;

/**
 是图片 传过来图片数组
 */
@property (nonatomic, strong) NSArray <UIImage *> *photos;

@end

@implementation HJTeasingDetailHeaderView

-(instancetype)init {
    if (self == [super init]) {
        self = [[NSBundle mainBundle]loadNibNamed:@"HJTeasingDetailHeaderView" owner:nil options:nil].firstObject;
        [self layerSubview];
    }
    return self;
}
-(void)layerSubview {
//    [self commitRAC];
    
    [self setupShadowWithView:self.titleView];
    [self setupShadowWithView:self.textView];
    [self setupShadowWithView:self.publicView];
    [self setupShadowWithView:self.contactView];
    
    [self.publicTitleView rounded:(UIRectCornerTopLeft | UIRectCornerTopRight) radius:6];
    [self.imagesView rounded:(UIRectCornerBottomLeft | UIRectCornerBottomRight) radius:6];
    [self.addBtn rounded:UIRectCornerAllCorners radius:6];
    [self.commitBtn rounded:UIRectCornerAllCorners radius:6];
    
    @weakify(self)
    [[self.textView.rac_textSignal filter:^BOOL(NSString * _Nullable value) {
        return value.length >=200;
    }] subscribeNext:^(NSString * _Nullable x) {
        @strongify(self)
        self.textView.text = [x substringToIndex:200];
    }];
    
    [mNotificationCenter addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:nil];

    [[self.addBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self addImage];
    }];
    
    [[self.commitBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        if (self.commitBlock) {
            self.commitBlock(self.phoneNum.text, self.textView.text, self.photos,self->_model.typeId);
        }
    }];
}


-(void)setModel:(HJTeasingModel *)model {
    _model = model;
    self.title.text = model.name;
}

-(void)textViewDidChange:(NSNotification *)textView {
    if (self.textView.text.length) {
        _placeHolder.hidden = YES;
    }else{
        _placeHolder.hidden = NO;
    }
    UITextInputMode *mode = (UITextInputMode *)[UITextInputMode activeInputModes][0];
    NSString *lang = mode.primaryLanguage;
    static NSInteger length = 0;
    if ([lang isEqualToString:@"zh-Hans"]) {
        UITextRange *selectedRange = [self.textView markedTextRange];
        if (!selectedRange) {
            length = self.textView.text.length;
        }
    }else{
        length = self.textView.text.length;
    }
    self.countLabel.text = [NSString stringWithFormat:@"%zd/200",length];
}
-(void)addImage {
    @weakify(self)
    [YFImagePicker multiplePickerWithMaxImagesCount:9 selecteImages:self.assets completedWithImages:^(NSArray<UIImage *> * _Nonnull photos, NSArray<PHAsset *> * _Nonnull assets, BOOL isSelectOriginalPhoto) {
        @strongify(self)
        self.photos = photos;
        self.assets = assets;
    }];
}

/**
 @param photos 图片数组
 */
-(void)setPhotos:(NSArray<UIImage *> *)photos {
    _photos = photos;
    static NSInteger count = 4;
    NSMutableArray <YBImageBrowseCellData *> *imageCellDatas = [NSMutableArray arrayWithCapacity:9];
    for (UIView *view in self.imagesView.subviews) {
        if ([view isKindOfClass:[UIImageView class]]) {
            [view removeFromSuperview];
        }
    }
    if (photos.count == 0) {
        self.addBtn_x.constant = 12;
        self.addBtn_y.constant = 10;
        return;
    }
    CGFloat imageWidth = (imageView_Width - margin * (count + 1)) / count;
    CGFloat imageHeight = imageWidth;
    NSInteger totalCount = photos.count + 1;
    
    for (int i =0; i<totalCount; i++) {
        NSInteger row = i / count;
        NSInteger col = i % count;
        CGFloat imageX = margin + (margin + imageWidth) * col;
        CGFloat imageY = margin + (margin + imageHeight) * row;
        // 图片按钮 重新赋值
        if (i == photos.count) {
            self.addBtn_x.constant = imageX;
            self.addBtn_y.constant = imageY;
            self.addBtn_width.constant = imageWidth;
            [self.addBtn rounded:UIRectCornerAllCorners radius:6];
            continue;
        }
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, imageWidth, imageHeight)];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.userInteractionEnabled = YES;
        imageView.tag = i;
        imageView.image = photos[i];
        [imageView rounded:(UIRectCornerAllCorners) radius:6];
        [self.imagesView addSubview:imageView];
        
        UIImageView * removeBtn = [UIImageView new];
        [removeBtn setImage:setImage(@"closeImage")];
        removeBtn.frame = CGRectMake(CGRectGetMaxX(imageView.frame)-removeBtn.image.size.width/2, removeBtn.image.size.height/2+imageY-margin, removeBtn.image.size.width, removeBtn.image.size.height);
        removeBtn.tag = i;
        removeBtn.contentMode = UIViewContentModeScaleAspectFill;
        removeBtn.userInteractionEnabled = YES;
        [self.imagesView addSubview:removeBtn];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBrowserImages:)];
        [imageView addGestureRecognizer:tap];
        UITapGestureRecognizer *removeTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeImages:)];
        [removeBtn addGestureRecognizer:removeTap];
        
        // 查看大图
        YBImageBrowseCellData *data = [YBImageBrowseCellData new];
        data.imageBlock = ^__kindof UIImage * _Nullable{
            return photos[i];
        };
        data.sourceObject = imageView;
        [imageCellDatas addObject:data];
    }
    self.imageCellDatas = imageCellDatas;
    
    // 一共有多少行
    NSInteger rows = ceil((double)totalCount / count);
    CGFloat imagesViewHeight = margin * (rows + 1) + imageHeight * rows;
    self.imagesView_H.constant = imagesViewHeight;
    [self.imagesView rounded:(UIRectCornerBottomLeft | UIRectCornerBottomRight) radius:6];
    [UIView animateWithDuration:0.25 animations:^{
        [self layoutIfNeeded];
    }];
    
}
#pragma 查看大图
-(void)showBrowserImages:(UITapGestureRecognizer *)tap {
    YBImageBrowser *browser = [YBImageBrowser new];
    [browser.defaultToolBar hideOperationButton];
    [browser.defaultSheetView setHidden:YES];
    NSInteger currentIndex = tap.view.tag;
    browser.dataSourceArray = _imageCellDatas;
    browser.currentIndex = currentIndex;
    [browser show];
}
#pragma 删除图片
-(void)removeImages:(UITapGestureRecognizer *)tap {
    NSMutableArray * photosArr = [NSMutableArray arrayWithArray:self.photos];
    [photosArr removeObjectAtIndex:tap.view.tag];
    NSMutableArray * assetsArr = [NSMutableArray arrayWithArray:self.assets];
    [assetsArr removeObjectAtIndex:tap.view.tag];
    self.photos = photosArr.mutableCopy;
    self.assets = assetsArr.mutableCopy;
    [UIView animateWithDuration:0.25 animations:^{
        [self layoutIfNeeded];
    }];
}

-(void)commitRAC {
    @weakify(self)
    [[self.phoneNum.rac_textSignal filter:^BOOL(NSString * _Nullable value) {
        return value.length >=11;
    }]subscribeNext:^(NSString * _Nullable x) {
        @strongify(self)
        self.phoneNum.text = [x substringToIndex:11];
    }];
    
//    RAC(self.commitBtn,userInteractionEnabled)= [RACSignal combineLatest:@[self.phoneNum.rac_textSignal] reduce:^id (NSString * phoneNum) {
//        @strongify(self)
//        if (phoneNum.length ==11 && [CommonTools isMobileNumber:phoneNum]) {
//            self.commitBtn.backgroundColor = [UIColor colorWithHex:0x2a2a2a];
//            return @YES;
//        }
//        self.commitBtn.backgroundColor = [UIColor lightGrayColor];
//        return @NO;
//    }];
}
@end


